import React from 'react';
import { Form, Row, Col, Input, Button, message } from 'antd';
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
import { ASelect, ASelectOptionType } from '@/components/SelfComp';
import { CqTradeItem } from '@/types/cq';
import { DataItem, FormProps } from '@/types/global';
import { TradeItem } from '@/types/trade';
import { formLayout, basicFormItemLangLayout, maxFormItemLayout } from '@/utils/commons';

type CqTradeInfoFormProps<T> = FormProps<T> & {
  /** 交易列表 */
  tradeData: TradeItem[];
  /** 正在查询交易下拉框 */
  queryLoading: boolean;
  addTrade2Table: (record: CqTradeItem) => Promise<boolean>;
}

type CqTradeInfoFormPropsEx<T> = Omit<CqTradeInfoFormProps<T>, 'formData'>;

const FormItem = Form.Item;
let tradeId: string;

const CqTradeInfoForm: React.FC<CqTradeInfoFormPropsEx<CqTradeItem>> = (props) => {

  const [form] = Form.useForm<CqTradeItem>();

  /**
   * 交易功能码栏位改变事件
   * 清除交易功能码栏位时，同时清除交易名称和交易路径两个栏位
   */
  const funcCodeChange = (value: string, _option: ASelectOptionType | ASelectOptionType[]) => {
    // 查询该功能码对应的交易信息
    // console.log('funcCodeChange');
    // console.log(option);
    if (value) {
      const { tradeData } = props;
      for (let i = 0; i < tradeData.length; i += 1) {
        const tmpItem =  tradeData[i];
        if (tmpItem.funcCode === value) {
          const { funcName, funcAction } = tmpItem;
          tradeId = tmpItem.tradeId;
          form.setFieldsValue({
            funcName,
            funcAction
          });
          break;
        }
      }
    } else {
      form.resetFields([
        'funcName','funcAction'
      ]);
    }
  }

  /**
   * 将选择的交易添加到表格中
   */
  const addTradeToTable = () => {
    // 交易功能码栏位的值添加到表格中
    // 如果交易功能码，交易名称，交易路径为则不允许添加
    // console.log(formRef.current);
    const funcCode = form.getFieldValue('funcCode');
    const funcName = form.getFieldValue('funcName');
    const funcAction = form.getFieldValue('funcAction');
    // console.log(funcCode);
    // console.log(funcName);
    // console.log(funcAction);
    if (!funcCode) {
      message.warning('请先选择交易');
      return;
    }
    if (!funcName || !funcAction) {
      message.warning('交易信息不全，请联系系统负责人');
      return;
    }
    const { addTrade2Table } = props;
    if (addTrade2Table) {
      // 添加交易时，默认已分配任务数量为0
      const record: CqTradeItem = {
        tradeId,
        funcCode,
        funcName,
        funcAction,
        taskNum: 0,
      };
      addTrade2Table(record).then(res => {
        if (res) {
          // 添加至表格后，清空交易三栏位
          form.resetFields([
            'funcCode','funcName','funcAction'
          ]);
        }
      });
    }
  }

  /**
   * 表单提交
   */
  const handleSubmit = () => {
    // 收集表单数据
    // 传递回父组件
    // 将交易及交易任务提交服务器端
    // console.info('AllotCqTrade.handleSubmit');
    const { onSubmit } = props;
    if (onSubmit) {
      onSubmit();
    }
  }

  const handleQuit = () => {
    // 先清除form表单
    form.resetFields();
    const { onCancel } = props;
    if (onCancel) {
      onCancel();
    }
  }

  const getFuncData = (tradeData: TradeItem[]) => {
    // console.info('getFuncData集合转换');
    let funcCodeData: DataItem[] = [];
    if (tradeData) {
      tradeData.forEach((item: TradeItem) => {
        const funcItem: DataItem = {
          key: item.funcCode,
          value: item.funcName
        }
        funcCodeData.push(funcItem);
      });
    }
    return funcCodeData;
  }

  const memoizeOneGetFuncData = memoizeOne(getFuncData, isEqual);

  const { colon, loading, queryLoading, tradeData } = props;
  // 8-16布局
  // 8-16布局
  const formItemLangLayout = basicFormItemLangLayout;
  const funcCodeData = memoizeOneGetFuncData(tradeData);

  return (
    <React.Fragment>
      <Form
        layout={formLayout}
        form={form}
        onFinish={handleSubmit}
      >
        <Row>
          <Col span={12}>
            <Form.Item label='交易功能码' {...formItemLangLayout} colon={colon}>
              <Row gutter={8}>
                <Col span={12}>
                  <Form.Item
                    name='funcCode'
                    noStyle
                  >
                    <ASelect dataSource={funcCodeData} type='1' onChange={funcCodeChange} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Button loading={queryLoading} onClick={() => addTradeToTable()} type='primary'>添加交易</Button>
                </Col>
              </Row>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <FormItem label='交易名称' name='funcName' {...maxFormItemLayout} colon={colon}>
              <Input disabled />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <FormItem label='交易路径' name='funcAction' {...maxFormItemLayout} colon={colon}>
              <Input disabled />
            </FormItem>
          </Col>
        </Row>
        <Row justify='center'>
          <Col>
            <FormItem>
              <Button type='primary' loading={loading} htmlType='submit'>
                提交
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={handleQuit}>返回</Button>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </React.Fragment>
  );
}

export default CqTradeInfoForm;